<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools>
        <!-- vue2.6以前的老式写法👇 -->
        <!-- <span slot="before">左</span> -->
        <!-- vue2.6以后的标准写法👇 -->
        <!-- <template v-slot:before></template>简写↓ -->
        <template #before>
          <span>当前共有{{ page.total }}条记录</span>
        </template>
        <template #after>
          <el-button type="danger" size="small" @click="onExport">员工导出</el-button>
          <el-button type="success" size="small" @click="$router.push('/import')">员工导入</el-button>
          <el-button type="primary" size="small" @click="showAddEmp = true">新增员工</el-button>
        </template>
      </PageTools>
      <!-- 渲染列表信息 -->
      <el-card>
        <el-table :data="list" :border="true" style="width:100%">
          <el-table-column label="序号" type="index"></el-table-column>
          <el-table-column sortable label="姓名" prop="username"></el-table-column>
          <el-table-column label="头像" prop="staffPhoto" width="120">
            <template v-slot="{ row }">
              <img
                v-imgerror="require('../../assets/common/img.jpeg')"
                :src="row.staffPhoto"
                style="border-radius:50%;width:100px;height:100px"
                @click="onshowQrcodDialog(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column sortable label="手机号" prop="mobile"></el-table-column>
          <el-table-column sortable label="工号" prop="workNumber"></el-table-column>
          <el-table-column sortable label="聘用形式" prop="formOfEmployment">
            <template v-slot="{ row }">
              {{ row.formOfEmployment | formatFormOfEmployment }}
            </template>
          </el-table-column>
          <el-table-column sortable label="部门" prop="departmentName"></el-table-column>
          <el-table-column sortable label="入职时间">
            <template v-slot="{ row }">
              <!-- 引入dayjs日期过滤器 -->
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column sortable label="账号状态" prop="enableState">
            <template v-slot="{ row }">
              <el-switch v-model="row.enableState" :active-value="1" :inactive-value="0" disabled>
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column sortable label="操作" width="260">
            <template #default="{ row }">
              <!-- 路由跳转方式 1：通过路劲字符串 -->
              <el-button type="text" @click="$router.push('/employees/detail/' + row.id)">查看</el-button>
              <!-- 路由跳转方式 2：通过name+对象 -->
              <!-- <el-button type="text" @click="$route.push({name:'detail',params:{id:row.id}})">查看</el-button> -->
              <el-button type="text">转正</el-button>
              <el-button type="text">调岗</el-button>
              <el-button type="text">离职</el-button>
              <el-button type="text" @click="onShowAsignRole(row.id)">角色</el-button>
              <el-button type="text" @click="onDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="end">
          <el-pagination
            layout="prev, pager, next"
            :total="page.total"
            :page-size="page.size"
            @current-change="onPageChange"
          ></el-pagination>
        </el-row>
      </el-card>
    </div>
    <!-- 图片预览弹框 -->
    <el-dialog title="图片预览" :visible.sync="showQrcodDialog" width="30%">
      <el-row type="flex" justify="center">
        <qrcode-vue :value="imgUrl" :size="size" level="H"></qrcode-vue>
      </el-row>
    </el-dialog>
    <add-emp :show-add-emp.sync="showAddEmp" @success="getEmployeesFn"></add-emp>
    <!-- 分配角色 -->
    <el-dialog title="分配角色" width="50%" :visible.sync="showAsignRoleDialog">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="(item, index) in roleList" :key="index" :label="item.id">{{ item.name }}}</el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-button size="small" @click="showAsignRoleDialog = false">取消</el-button>
        <el-button type="primary" size="small" @click="onAsignRole">确定</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { pick } from 'lodash'// 引用lodash中的pick方法过滤
import { assignRoles, delEmployees, getEmployeeBaseInfo, getEmployees } from './employees'
import QrcodeVue from 'qrcode.vue'
import AddEmp from './components/addEmp.vue'
import { formatDate, formatFormOfEmployment } from '@/filters'
import { getRoles } from '@/api/setting'
export default {
  name: 'Employees',
  components: {
    QrcodeVue,
    AddEmp
  },
  data() {
    return {
      showQrcodDialog: false,
      showAddEmp: false,
      showAsignRoleDialog: false,
      checkList: ['选中且禁用', '复选框 A'],
      size: 100,
      imgUrl: '',
      list: [],
      // 定义分页数据
      page: {
        page: 1,
        size: 2,
        total: 0
      },
      // 定义角色列表和选中角色id数组
      roleList: [],
      roleIds: [],
      currenUserId: undefined// 定义当前的用户id
    }
  },
  created() {
    this.getEmployeesFn()
    this.getRolesFn()
  },
  mounted() { },
  methods: {
    // 点击角色获取当前角色信息回显
    async onShowAsignRole(id) {
      this.currenUserId = id
      // 获取当前用户信息
      const { roleIds } = await getEmployeeBaseInfo(id)
      this.roleIds = roleIds
      // 显示对话框
      this.showAsignRoleDialog = true
    },
    async getRolesFn() {
      // 公司设置=====角色管理
      const { rows } = await getRoles({ page: 1, pagesize: 10 })
      this.roleList = rows
    },
    // 角色分配确定
    async onAsignRole() {
      // 发请求
      await assignRoles({
        id: this.currenUserId,
        roleIds: this.roleIds
      })
      // 提示成功
      this.$message.success('操作成功')
      // 关闭对话框
      this.showAsignRoleDialog = false
    },
    // 导出exl表
    onExport() {
      import('@/vendor/Export2Excel').then(async excel => {
        const headers = {
          '手机号': 'mobile',
          '姓名': 'username',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        const { rows } = await getEmployees({ page: 1, size: this.page.total })// 获取数据
        // 引用lodash中的pick方法过滤
        const header = Object.keys(headers)
        const data = rows.map(t => {
          // 返回所有的值
          // console.log(Object.values(t))
          // return Object.values(t)
          // 过滤对象
          const m = pick(t, Object.values(headers))
          // console.log(m)
          m.timeOfEntry = formatDate(m.timeOfEntry)// 时间格式化（formatDate是dayjs的）
          m.correctionTime = formatDate(m.correctionTime)
          m.formOfEmployment = formatFormOfEmployment(m.formOfEmployment)
          return Object.values(m)
        })
        // console.log(header)
        // console.log(data)

        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    // 点击列表删除员工信息
    onDel(id) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async action => {
        await delEmployees(id)
        this.$message('操作成功')
        this.getEmployeesFn()
      })
    },
    // 渲染角色列表
    async getEmployeesFn() {
      const { total, rows } = await getEmployees(this.page)
      this.page.total = total
      this.list = rows
    },
    onPageChange(val) {
      // 角色列表翻页
      this.page.page = val
      this.getEmployeesFn()
    },
    // 点击显示图片预览框
    onshowQrcodDialog(url) {
      if (url) {
        this.imgUrl = url
      } else {
        this.imgUrl = 'https://img0.baidu.com/it/u=1705694933,4002952892&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=281'
      }
      this.showQrcodDialog = true
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
